<template>

    <div class="container">
        <m-header>
            {{title}}
        </m-header>

        <div class="main">
            <div class="box passenger-wrap">
                <div class="cell">
                    <div class="label">订单编号</div>
                    <div class="value">{{out_trade_no}}</div>
                </div>
                <!--<van-button class="btn" color="#24C373" v-prevent-re-click @click="searchRecord">查询</van-button>-->
            </div>

            <van-calendar ref="calendarRef"
                    v-model="showCalendar" title="请假日期" :formatter="formatter" :poppable="false" color="#24C373" type="multiple"
                    :min-date="minDate" :max-date="maxDate" :show-confirm="false" :readonly="readonly"
                    @select="onSelect" @unselect="onUnSelect">
                <template #bottom-info="day" >
                    <div class="bot-info" v-if="item = check(day)">
                        <div class="label up" v-if="item.up">上</div>
                        <div class="label down" v-if="item.down">放</div>
                    </div>
                </template>
            </van-calendar>
        </div>

        <van-popup v-model="showPopup" closeable round :close-on-click-overlay="false" duration="0.2">
            <div class="popup-wrap">
                <div class="title">登记请假方向</div>
                <div class="content">
                    <div class="date">请假日期：{{leaveDate}}</div>
                    <div class="checkbox-wrap">
                        <van-checkbox class="checkbox" v-model="leaveUp" checked-color="#24C373" shape="square">去程</van-checkbox>
                        <van-checkbox class="checkbox" v-model="leaveDown" checked-color="#24C373" shape="square">回程</van-checkbox>

                    </div>
                    <div class="cell" v-for="(item,index) in fieldList">

                        <m-form
                                :key="index"
                                :field="item"
                                :disabled="false"
                                :value="value[item.field_id]"
                                @change="onChange"></m-form>


                    </div>
                </div>
                <div class="btn-wrap">
                    <van-button class="btn" color="#24C373" @click="onConfirm" v-prevent-re-click>确定</van-button>

                </div>
            </div>
        </van-popup>
    </div>
</template>

<script>
  import form from '@/components/form/form'
  import field from '@/components/field/field'
  import list from '@/components/list/list';
  import {mapState} from 'vuex'
  import {getOrder, getLeaveRegistration,addLeaveRegistration,editLeaveRegistration,delLeaveRegistration} from "../../request/api";
  import {preventReClick} from "../../utils/plugins";
  import {Popup,Calendar,Checkbox} from 'vant';
  import {getSession,removeSession} from "../../utils/store";
      import {crtTimeFtt} from "../../utils/utils";
      import dialog from '@/utils/dialog';

  export default {
    name: "leaveAsk",
    components:{
      mForm: form,
      mField: field,
      mList: list,
      [Calendar.name]:Calendar,
      [Popup.name]: Popup,
      [Checkbox.name]: Checkbox
    },
    computed:{
      ...mapState({
        customerId: state => state.user.customerId
      }),

      selected() {
        let rowData = [...this.rowData]
        return function(day){
          let exist = rowData.find(item =>{
              return crtTimeFtt(item.leave_date,'YYYY-MM-DD') === crtTimeFtt(day.date,'YYYY-MM-DD')
            });
          if (exist){
            return {
              up: exist && exist.is_leave_on_gotoschool,
              down: exist && exist.is_leave_on_leaveschool
            }
          }
        }
      },
    },
    watch:{
      ['$route']: {
        handler(val){
          if (val.path === '/leaveAsk'){
            let query = val.query,
              {id,type} = query;
            this.out_trade_no = id;
            this.getOrder();
            this.getLeave();
            this.readonly = type === 'readonly'
            this.title = type === 'readonly' ? '登记记录' : '请假登记'
          }
        },immediate: true
      },

      showPopup(val){
        if (!val){
          this.$refs.calendarRef.reset([...this.selectedDate])
        }
      }
    },
    data(){
      return {
        // 录入字段参数
        fields: [
          {
            label: '订单编号',
            type: 'text',
            disabled: true,
            field_id: 'order_no',
          }, /*   {
             label: '请假日期起日',
             type: 'date',
             disabled: false,
             field_id: 'identification_no',
           },*/
        ],
        value: {},
        list: [],
        total: 0,
        size: 10,
        no:1,
        loading: false,
        loadEnd: true,
        showCalendar: true,
        selectedDate: [],
        // calendarRef: null,
        minDate: new Date(),
        maxDate: new Date(),
        readonly: true,
        title: '',

        //显示登记弹窗
        showPopup: false,
        leaveUp: false,
        leaveDown: false,
        leaveDate: '',
        fieldList: [
          {
            label: '学生学号',
            type: 'text',
            field_id: 'student_id',
          },
          {
            label: '摘要',
            type: 'textarea',
            field_id: 'abstract_',
          },
        ]
      }
    },
    methods:{
      onChange(e){
        let {field,val} = e,
          {field_id} = field;
        this.value[field_id] = val;
        console.log(this.value);
      },

      onSelect(val){
        let newDate = val[val.length-1],
            selectedDate = crtTimeFtt(newDate,'YYYY-MM-DD');
        this.onShowPopup(selectedDate)
          /*dialog.confirm('确定提交请假登记？',`请假日期：${selectedDate}`).then(() => {
            console.log('确定请假');
            this.$Loading()
            this.addLeave(selectedDate).then(()=>{
                this.$Toast('登记成功');
                this.getLeave();
            })
            // this.selectedDate.push(newDate)
        },()=>{
            console.log('取消确定1');
            this.$refs.calendarRef.reset([...this.selectedDate])
        })*/
      },
      onUnSelect(val){
        let unselectDate = crtTimeFtt(val,'YYYY-MM-DD')
        this.onShowPopup(unselectDate)
          /*dialog.confirm('确定取消请假登记？',`取消日期：${unselectDate}`).then(() => {
              console.log('确定取消');
              this.$Loading()
              this.delLeave(unselectDate).then(()=>{
                this.$Toast('取消成功')
                this.getLeave();
                  /!*this.selectedDate = this.selectedDate.filter(item =>{
                      let date = crtTimeFtt(item,'YYYY-MM-DD');
                      return date !== unselectDate
                  })*!/
              },() => this.$refs.calendarRef.reset([...this.selectedDate]) )
          },()=>{
              console.log('取消确定2');
              this.$refs.calendarRef.reset([...this.selectedDate]);
          })*/
      },
      //格式化日历
      formatter(day) {
          let selectedDate = [...this.selectedDate],
              exit = selectedDate.some(item =>{
                  return crtTimeFtt(item,'YYYY-MM-DD') === crtTimeFtt(day.date,'YYYY-MM-DD')
              });
          if (exit) {
              day.bottomInfo = '请假';
              day.className = 'leave-bg'
          }
        /*if (['multiple-selected','start','end','selected','multiple-middle'].includes(day.type)) {
          day.bottomInfo = '请假';
        }*/
        return day;
      },

      //  获取订单
      getOrder(){
        this.$Loading();
        let post = {out_trade_no: this.out_trade_no}
        getOrder(post).then(res => {
          if (res.errcode !== 0)return;
          this.$toast.clear();
          let data = res.row[0];
          if (!data) return
          let {Order_create_time,Order_status,effective_time_start,effective_time_end} = data;
          let nowTime = new Date(),
            minDate = new Date(effective_time_start),
            maxDate = new Date(effective_time_end);

          if (!this.readonly && nowTime.getTime() > minDate.getTime()){
            minDate = nowTime;
          }
          this.$refs.calendarRef.scrollToDate(minDate)
          // console.log();
          this.minDate = minDate;
          this.maxDate = maxDate;


        })
      },

    // 获取请假登记记录
      getLeave(){
        this.$Loading();
        getLeaveRegistration({out_trade_no: this.out_trade_no}).then(res =>{
          if (res.errcode != 0) return;
          let data = res.row || [],
            dates = [];
          data.forEach(item =>{
            if (item.is_leave_on_gotoschool || item.is_leave_on_leaveschool) dates.push(new Date(item.leave_date))
          })
          this.selectedDate = dates;
          this.$refs.calendarRef.reset([...this.selectedDate])
          this.rowData = data;
          this.$toast.clear();

        })
      },

      onShowPopup(date){
        this.leaveDate = date;
        let exist = this.rowData.find(item => crtTimeFtt(item.leave_date,'YYYY-MM-DD') === date);
        this.leaveUp = exist && exist.is_leave_on_gotoschool;
        this.leaveDown = exist && exist.is_leave_on_leaveschool;
        let value = this.value;
        if (exist){
          exist.student_id && (value.student_id = exist.student_id);
          exist.abstract && (value.abstract = exist.abstract);
        }
        this.value = value;

        this.showPopup = true;
      },
      onConfirm(){
        let {leaveDate,leaveUp,leaveDown,rowData,value} = this,
          exist = rowData.find(item => crtTimeFtt(item.leave_date,'YYYY-MM-DD') === leaveDate),
          post = {
            out_trade_no: this.out_trade_no,
            leave_date: leaveDate,
            customer_id: this.customerId,
            is_leave_on_gotoschool: leaveUp,
            is_leave_on_leaveschool: leaveDown,
            ...value
          },
          type = exist ? 'edit' :'add'

        //未提交申请且没有勾选
        if (!exist && !leaveUp && !leaveDown){
          this.showPopup = false;
          return
        }
        //已有申请
        if (exist){
          post.row_id = exist.row_id;
          //取消申请，删除
          if (!leaveUp && !leaveDown) {
            type = 'del';
            post = exist.row_id
          }
        }
        this.$Loading();
        this.submitLeave(post,type).then(res =>{
          this.$Toast('登记成功')
          this.getLeave();
          this.showPopup = false;
        })
      },

      submitLeave(param,type){
        return new Promise(resolve => {
          let api = type === 'add' ? addLeaveRegistration : type === 'edit' ? editLeaveRegistration : delLeaveRegistration;
          api(param).then(res =>{
            if (res.errcode != 0) return;
            resolve()
          })
        })
      },

      check(day){
        if (!this.rowData) return
          let exist = this.rowData.find(item =>{
            return crtTimeFtt(item.leave_date,'YYYY-MM-DD') === crtTimeFtt(day.date,'YYYY-MM-DD')
          });
          if (exist){
            return {
              up: exist && exist.is_leave_on_gotoschool,
              down: exist && exist.is_leave_on_leaveschool
            };
          }
      },

    //   申请请假
      addLeave(date){
          return new Promise(resolve => {
            addLeaveRegistration({
              out_trade_no: this.out_trade_no,
              leave_date: date,
              customer_id: this.customerId
            }).then(res =>{
              if (res.errcode != 0) return;
              resolve()
            })
          })
        },
      editLeave(id){
        return new Promise(resolve => {
          addLeaveRegistration({
            out_trade_no: this.out_trade_no,
            leave_date: date,
            customer_id: this.customerId
          }).then(res =>{
            if (res.errcode != 0) return;
            resolve()
          })
        })
      },
      // 删除请假申请
      delLeave(date){
          return new Promise((resolve,reject) => {
            let {rowData} = this,
              delData = rowData.find(item => crtTimeFtt(item.leave_date,'YYYY-MM-DD') === date);
            if (!delData) {
              resolve();return;
            }
            delLeaveRegistration(delData.row_id).then(res =>{
              if (res.errcode != 0) return;
              resolve()
            },reject)
          })
        },


    },
    mounted(){

    }
  }
</script>

<style scoped lang="less">
    .h-btn{
        padding-right: 10px;
    }
    .main{
        padding: 10px;
        display: flex;
        flex-direction: column;
        flex: 1;
        height: 0;
        .box{
            background: #fff;
            border-radius: 2px;
            margin-bottom: 10px;
            padding: 10px 15px ;
            .cell{
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 15px;
                height: 44px;
                border-bottom: 1px solid #dedede;
                .cell-right{
                    text-align: right;
                    flex: 1;
                    .cell-value{
                        text-align: right;
                    }
                }
            }
            .btn{
                width: 100%;
                margin-top: 10px;
            }
        }
        .leave-bg{
            background: #24C373;
        }
        ::v-deep{
            .van-calendar{
                flex: 1;
                height: 0;

                .leave-bg{
                    background: #24C37366;
                    border-radius: 4px;
                }

                .bot-info{
                    display: flex;
                    justify-content: center;
                    .label{
                        width: 16px;
                        height: 16px;
                        border-radius: 16px;
                        color: #ffffff;
                        text-align: center;
                        line-height: 16px;
                        background: #ffffff;
                        &.up{
                            border: 1px solid #00a041;
                            color: #24C373;
                        }
                        &.down{
                            border: 1px solid #ff300d;
                            color: #ff300d;
                        }
                    }
                }
            }
        }
        .list-wrap{
            flex: 1;

        }
    }

    .popup-wrap{
        width: 90vw;
        /*width: 70vw;*/
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 500px;
        /*height: 250px;*/
        .title{
            padding: 15px 15px 10px;
            color: #333333;
            font-size: 17px;
            font-weight: bold;
        }
        .content{
            flex: 1;
            height: 0;
            padding: 0 30px;
            width: 100%;
            box-sizing: border-box;
            .date{
                padding: 20px 0;
                font-size: 18px;
            }
            .checkbox-wrap{
                display: flex;
                font-size: 18px;
                .checkbox{
                    margin-right: 20px;
                }
            }

            .cell{
                border-radius: 4px;
                border: 1px solid #e6e6e6;
                margin-top: 20px;
                padding: 0 10px;
            }
        }
        .btn-wrap{
            width: 100%;
            padding: 5px 15px 15px;
            box-sizing: border-box;
            .btn{
                width: 100%;
            }
        }

    }
</style>
